package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

@Slf4j
@Component
public class OrderTask {
    @Autowired
    private OrderMapper orderMapper;

                    //秒 分 时 日 月 星期（没有年，Task为弱化）
//    @Scheduled(cron = "0 * * * * ?")    //每分钟执行一次
//    @Scheduled(cron = "0/5 * * * * ?")
    public void processTimeoutOrder(){
        log.info("处理支付超时订单：{}",new Date());
        LocalDateTime localDateTime = LocalDateTime.now().plusMinutes(-15);//当前时间-15分钟
        List<Orders> ordersList = orderMapper.getByStatusAndOrdertimeLT(Orders.PENDING_PAYMENT, localDateTime);//状态为 待支付，时间超过15分钟
        ordersList.forEach(orders -> {
            orders.setStatus(Orders.CANCELLED);
            orders.setCancelTime(LocalDateTime.now());
            orders.setCancelReason("支付超时，自动取消");
            orderMapper.update(orders);
        });
    }

//    @Scheduled(cron = "0 0 1 * * ?")//每天1点执行
//    @Scheduled(cron = "1/5 * * * * ?")
    public void processDeliveryOrder(){
        log.info("处理派送中的订单：{}",new Date());
        LocalDateTime localDateTime = LocalDateTime.now().plusHours(-1);
        List<Orders> ordersList = orderMapper.getByStatusAndOrdertimeLT(Orders.DELIVERY_IN_PROGRESS, localDateTime);
        if (ordersList != null && ordersList.size() > 0) {
            ordersList.forEach(orders -> {
                orders.setStatus(Orders.COMPLETED);
                orderMapper.update(orders);
            });
        }
    }


}
